package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.domain.entity.PaasAppEntity;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.AliasEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.factory.MarketingFieldHelp;
import com.xbongbong.pro.enums.errorcodes.AppStoreErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.MarketingErrorCodeEnum;
import com.xbongbong.sys.help.ProPermissionHelp;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.ButtonPojo;
import com.xbongbong.paas.pojo.DataDetailPojo;
import com.xbongbong.paas.pojo.DetailTabPojo;
import com.xbongbong.paas.pojo.DetailTitlePojo;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.pojo.dto.FormDataGetDTO;
import com.xbongbong.paas.pojo.vo.AfterSaveVO;
import com.xbongbong.paas.service.CouponTempleteService;
import com.xbongbong.paas.service.MarketingManagementService;
import com.xbongbong.paas.service.PromotionActivityService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.appdetail.pojo.MobileDetailSpecialInfoPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailStatusPojo;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.form.pojo.TopPermissionsPoJo;
import com.xbongbong.pro.formdata.pojo.dto.FormDataDetailDTO;
import com.xbongbong.pro.formdata.pojo.vo.FormDataDetailVO;
import com.xbongbong.pro.formdata.pojo.vo.MobileFormCommonDetailVO;
import com.xbongbong.pro.listbatch.pojo.dto.OnlineDTO;
import com.xbongbong.pro.marketing.pojo.MarketingManagementPojo;
import com.xbongbong.pro.marketing.pojo.dto.MarketingManagementAddGetDTO;
import com.xbongbong.pro.marketing.pojo.dto.MarketingManagementDTO;
import com.xbongbong.pro.marketing.pojo.dto.MarketingManagementDataAddDTO;
import com.xbongbong.pro.marketing.pojo.dto.MarketingManagementDataCopyDTO;
import com.xbongbong.pro.marketing.pojo.dto.MarketingManagementDataGetDTO;
import com.xbongbong.pro.marketing.pojo.dto.MarketingManagementDataUpdateDTO;
import com.xbongbong.pro.marketing.pojo.dto.MarketingManagementDataUpdateGetDTO;
import com.xbongbong.pro.marketing.pojo.dto.MarketingManagementDeleteBatchDTO;
import com.xbongbong.pro.marketing.pojo.vo.MarketingManagementAddGetVO;
import com.xbongbong.pro.marketing.pojo.vo.MarketingManagementDataAddVO;
import com.xbongbong.pro.marketing.pojo.vo.MarketingManagementDataCopyVO;
import com.xbongbong.pro.marketing.pojo.vo.MarketingManagementDataGetVO;
import com.xbongbong.pro.marketing.pojo.vo.MarketingManagementDataUpdateGetVO;
import com.xbongbong.pro.marketing.pojo.vo.MarketingManagementDataUpdateVO;
import com.xbongbong.pro.marketing.pojo.vo.MarketingManagementDeleteBatchVO;
import com.xbongbong.pro.marketing.pojo.vo.MarketingManagementVO;
import com.xbongbong.pro.permission.pojo.dto.VerifyViewPermissionDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.SaasButtonEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.MarketingActivityManagementEnum;
import com.xbongbong.saas.enums.business.MarketingBaseEnum;
import com.xbongbong.saas.enums.dictionary.ApplicableObjectTypeEnum;
import com.xbongbong.saas.enums.dictionary.InapplicableProductTypeEnum;
import com.xbongbong.saas.enums.dictionary.MarketingStatusEnum;
import com.xbongbong.saas.help.ExplainHelp;
import com.xbongbong.saas.help.MarketingHelp;
import com.xbongbong.saas.model.CouponTempleteModel;
import com.xbongbong.saas.model.PromotionActivityModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.CompanyEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.help.ProPermissionHelp;
import com.xbongbong.sys.model.CompanyModel;
import com.xbongbong.sys.model.UserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 营销管理服务
 * @author jyh
 * @date 2020/12/22 9:35
 * @since v1.0
 * @version v1.0
 */

@Service("marketingManagementService")
public class MarketingManagementServiceImpl implements MarketingManagementService {
    @Resource
    private PaasAppModel paasAppModel;
    @Resource
    private CompanyModel companyModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private CouponTempleteModel couponTempleteModel;
    @Resource
    private MarketingHelp marketingHelp;
    @Resource
    private CouponTempleteService couponTempleteService;
    @Resource
    private UserModel userModel;
    @Resource
    private MarketingFieldHelp marketingFieldHelp;
    @Resource
    private PromotionActivityService promotionActivityService;
    @Resource
    private PromotionActivityModel promotionActivityModel;
    @Resource
    private ExplainHelp explainHelp;

    private static final Logger LOG = LoggerFactory.getLogger(MarketingManagementServiceImpl.class);

    private static final String XBB_LOGO = "https://cdn3.xbongbong.com/xbbProPrd/dingfebc45745cb7863135c2f4657eb6378f/102448110321569562/png/1608692176846e86b9db064b2a91bd44a3f3a17c2bee5.png?1608692176846";


    @Override
    public MarketingManagementVO getActivityList(MarketingManagementDTO marketingManagementDTO) throws XbbException {

        String corpid = marketingManagementDTO.getCorpid();
        PaasAppEntity paasAppEntity = paasAppModel.getByKey(marketingManagementDTO.getAppId(), corpid);
        if (paasAppEntity == null) {
            throw new XbbException(AppStoreErrorCodeEnum.API_ERROR_300001);
        }
        MarketingManagementVO marketingManagementVO = new MarketingManagementVO();
        Integer businessType = marketingManagementDTO.getBusinessType();
        List<MarketingManagementPojo> activities;
        if (Objects.equals(businessType, XbbRefTypeEnum.MARKETING_ACTIVITY.getCode())) {
            activities = MarketingManagementPojo.getMarketingActivities();
        } else if (Objects.equals(businessType, XbbRefTypeEnum.PROMOTION_ACTIVITY.getCode())){
            activities = MarketingManagementPojo.getPromotionActivities();
        } else {
            activities = new ArrayList<>();
        }
        //获取新建权限按钮
        boolean addPermission = marketingHelp.verifyAddPermission(marketingManagementDTO.getLoginUser(), businessType);
        marketingManagementVO.setAddPermission(addPermission ? 1 : 0);
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType4Distributor(businessType, corpid, DistributorMarkEnum.DISTRIBUTOR.getCode(), null);
        marketingManagementVO.setAppId(marketingManagementDTO.getAppId());
        marketingManagementVO.setMenuId(marketingManagementDTO.getMenuId());
        marketingManagementVO.setFormId(paasFormEntityExt.getId());
        marketingManagementVO.setActivityList(activities);
        return marketingManagementVO;
    }


    @Override
    public MarketingManagementAddGetVO addGet(MarketingManagementAddGetDTO marketingManagementDTO) throws XbbException {
        MarketingManagementAddGetVO marketingManagementVO = new MarketingManagementAddGetVO();
        Integer businessType = marketingManagementDTO.getBusinessType();
        Integer subBusinessType = marketingManagementDTO.getSubBusinessType();
        //校验新建权限
        boolean addPermission = marketingHelp.verifyAddPermission(marketingManagementDTO.getLoginUser(), subBusinessType);
        if (!addPermission) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100050, String.format(SystemErrorCodeEnum.API_ERROR_100050.getMsg(), SaasButtonEnum.ADD.getValue()));
        }
        String corpid = marketingManagementDTO.getCorpid();
        CompanyEntity companyEntity = companyModel.getNormalCompanyByKey(corpid);
        marketingManagementVO.setCorpName(companyEntity.getCorpName());
        marketingManagementVO.setLogo(XBB_LOGO);
        //塞经销商级别
        List<ItemPoJo> distributorLevel = marketingHelp.getDistributorLevel(corpid);
        marketingManagementVO.setDistributorLevel(distributorLevel);
        //为了选择产品
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getSystemDefaultExplain(businessType);
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        //处理关联产品解释
        handleProductExplain(explainList, marketingManagementDTO);
        if (Objects.equals(subBusinessType, XbbRefTypeEnum.PROMOTION_ACTIVITY.getCode())) {
            marketingManagementVO.setPriorityLevel(marketingHelp.getPriorityLevel(corpid, businessType));
        }
        marketingManagementVO.setExplainList(explainList);
        return marketingManagementVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MarketingManagementDataAddVO add(MarketingManagementDataAddDTO marketingManagementDTO) throws XbbException {

        MarketingManagementDataAddVO marketingManagementDataAddVO = new MarketingManagementDataAddVO();
        try {
            Integer businessType = marketingManagementDTO.getBusinessType();
            Integer subBusinessType = marketingManagementDTO.getSubBusinessType();
            //新建权限校验
//            boolean addPermission = marketingHelp.verifyAddPermission(marketingManagementDTO.getLoginUser(), subBusinessType);
//            if (!addPermission) {
//                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100050, String.format(SystemErrorCodeEnum.API_ERROR_100050.getMsg(), SaasButtonEnum.ADD.getValue()));
//            }
            JSONObject data = marketingManagementDTO.getDataList();
            //校验数据格式
            validateData(data,businessType);
            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
            AfterSaveVO afterSaveVO;
            switch (xbbRefTypeEnum) {
                case FULL_DISCOUNT_COUPON:
                    afterSaveVO = couponTempleteService.add(marketingManagementDTO);
                    break;
                case SPECIAL_GOODS:
                    afterSaveVO = promotionActivityService.add(marketingManagementDTO);
                    break;
                default:
                    afterSaveVO = new AfterSaveVO();
            }
            if ( Objects.equals(afterSaveVO.getCode(), PaasConstant.FORM_ADD_PROCESS_RETURN_CODE) ) {
                marketingManagementDataAddVO.setMsg(afterSaveVO.getMsg());
                marketingManagementDataAddVO.setCode(afterSaveVO.getCode());
            }else {
                marketingManagementDataAddVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_RETURN_MSG));
                marketingManagementDataAddVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("MarketingManagement数据库保存表单数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return marketingManagementDataAddVO;
    }

    @Override
    public FormDataDetailVO getWebDetail(FormDataDetailDTO formDataDetailDTO) throws XbbException {
        FormDataDetailVO formDataDetailVO = new FormDataDetailVO();
        Integer subBusinessType = formDataDetailDTO.getBusinessType();
        Long dataId = formDataDetailDTO.getDataId();
        // 查看权限校验
        VerifyViewPermissionDTO verifyViewPermissionDTO = new VerifyViewPermissionDTO();
        BeanUtil.copyProperties(formDataDetailDTO, verifyViewPermissionDTO);
        verifyViewPermissionDTO.setMenuId(formDataDetailDTO.getMenuId());
        ProPermissionHelp.verifyQueryPermission(verifyViewPermissionDTO);
        String corpid = formDataDetailDTO.getCorpid();

        List<DetailTabPojo> tabPojoList = new ArrayList<>();
        // saas详情tab
        DataDetailPojo dataDetailPojo = new DataDetailPojo();
        List<ButtonPojo> buttonPojoList = new ArrayList<>();

        PaasFormDataEntityExt paasFormDataEntityExt = null;
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType4Distributor(subBusinessType, corpid, DistributorMarkEnum.DISTRIBUTOR.getCode(), null);
        formDataDetailVO.setPaasFormEntityExt(paasFormEntityExt);
        if (Objects.equals(subBusinessType, XbbRefTypeEnum.MARKETING_ACTIVITY_MANAGEMENT.getCode())) {
            paasFormDataEntityExt = couponTempleteModel.getByKey(dataId, corpid);

        }else if (Objects.equals(subBusinessType, XbbRefTypeEnum.PROMOTION_ACTIVITY_MANAGEMENT.getCode())){
            paasFormDataEntityExt = promotionActivityModel.getByKey(dataId, corpid);
        }
        Integer businessType = paasFormDataEntityExt.getBusinessType();
        JSONObject data = paasFormDataEntityExt.getData();
        //tab处理
        marketingHelp.handelDetailTab(businessType, tabPojoList, PlatFormEnum.WEB, formDataDetailDTO.getLoginUser(), data, corpid);
        //button处理
        marketingHelp.handelDetailButton(businessType, buttonPojoList,formDataDetailDTO.getLoginUser(), paasFormEntityExt, paasFormDataEntityExt.getStatus());
        // 详情标签、摘要(按顺序返回给前端)
        JSONArray secondTitle = new JSONArray();
        String addTime = DateTimeUtil.getStringEpochSecond(paasFormDataEntityExt.getAddTime());
        UserEntity userEntity = userModel.getByKey(paasFormDataEntityExt.getCreatorId(), corpid);
        String creatorName = "";
        if (Objects.nonNull(userEntity)) {
            creatorName = userEntity.getName();
        }
        JSONObject creatorTitleObj= ExplainUtil.getSecondTitleObj(false, MarketingActivityManagementEnum.CREATOR_ID.getAttrName(), creatorName);
        JSONObject addTimeTitleObj = ExplainUtil.getSecondTitleObj(false, MarketingActivityManagementEnum.ADD_TIME.getAttrName(), addTime);
        secondTitle.add(creatorTitleObj);
        secondTitle.add(addTimeTitleObj);
        DetailTitlePojo detailTitlePojo = new DetailTitlePojo();
        detailTitlePojo.setName(data.getString(MarketingBaseEnum.NAME.getAttr()));
        //不支持排序
        dataDetailPojo.setTabSortPermission(false);
        dataDetailPojo.setButton(buttonPojoList);
        dataDetailPojo.setTitle(detailTitlePojo);
        dataDetailPojo.setSecondTitle(secondTitle);
        formDataDetailVO.setHead(dataDetailPojo);
        formDataDetailVO.setTab(tabPojoList);
        return formDataDetailVO;
    }

    /**
     * 详情页基本信息
     * @param marketingManagementDTO
     * @return
     * @throws XbbException
     */
    @Override
    public MarketingManagementDataGetVO get(MarketingManagementDataGetDTO marketingManagementDTO) throws XbbException {
        MarketingManagementDataGetVO marketingManagementDataGetVO = new MarketingManagementDataGetVO();
        Long dataId = marketingManagementDTO.getDataId();
        String corpid = marketingManagementDTO.getCorpid();
        Integer subBusinessType = marketingManagementDTO.getBusinessType();
        PaasFormDataEntityExt paasFormDataEntityExt = null;
        if (Objects.equals(subBusinessType, XbbRefTypeEnum.MARKETING_ACTIVITY_MANAGEMENT.getCode())) {
            paasFormDataEntityExt = couponTempleteModel.getByKey(dataId, corpid);
            String name = marketingHelp.analysisCouponName(paasFormDataEntityExt.getName(), corpid, paasFormDataEntityExt.getBusinessType());
            paasFormDataEntityExt.getData().put(MarketingActivityManagementEnum.NAME.getAttr(), name);
        }else if (Objects.equals(subBusinessType, XbbRefTypeEnum.PROMOTION_ACTIVITY_MANAGEMENT.getCode())){
            paasFormDataEntityExt = promotionActivityModel.getByKey(dataId, corpid);
        }
        JSONObject data = paasFormDataEntityExt.getData();
        Integer businessType = paasFormDataEntityExt.getBusinessType();

        //解析区域字段
        marketingHelp.analysisLocation(data, corpid);
        if (Objects.equals(data.getString(MarketingBaseEnum.APPLICABLE_OBJECT_TYPE.getAttr()), ApplicableObjectTypeEnum.DISTRIBUTOR_LEVEL.getCode())){
            Map<String, String> distributorLevelMap = new HashMap<>();
            List<ItemPoJo> distributorLevel = marketingHelp.getDistributorLevel(corpid);
            distributorLevel.forEach(item -> distributorLevelMap.put(item.getValue().toString(), item.getText()));
            JSONArray levelArray = data.getJSONArray(MarketingBaseEnum.DISTRIBUTOR_LEVEL.getAttr());
            if (Objects.nonNull(levelArray) && !levelArray.isEmpty()) {
                JSONArray levels = new JSONArray();
                for (int i = 0; i < levelArray.size(); i++) {
                    String levelId = levelArray.getString(i);
                    if (distributorLevelMap.containsKey(levelId)) {
                        JSONObject level = new JSONObject();
                        level.put(StringConstant.SAAS_LINK_BUSINESS_ID, levelId);
                        level.put(StringConstant.SAAS_LINK_BUSINESS_NAME, distributorLevelMap.get(levelId));
                        levels.add(level);
                    }
                }
                data.put(MarketingBaseEnum.DISTRIBUTOR_LEVEL.getAttr(), levels);
            }
        }

        String addTime = DateTimeUtil.getStringEpochSecond(paasFormDataEntityExt.getAddTime());
        UserEntity userEntity = userModel.getByKey(paasFormDataEntityExt.getCreatorId(), corpid);
        String creatorName = "";
        if (Objects.nonNull(userEntity)) {
            creatorName = userEntity.getName();
        }
        data.put("creatorId", creatorName);
        data.put("addTime", addTime);
        data.put(MarketingBaseEnum.STATUS.getAttr(), MarketingStatusEnum.getByCode(paasFormDataEntityExt.getStatus()));
        marketingManagementDataGetVO.setBusinessType(businessType);
        marketingManagementDataGetVO.setData(data);
        return marketingManagementDataGetVO;
    }

    @Override
    public MarketingManagementDataUpdateGetVO updateGet(MarketingManagementDataUpdateGetDTO marketingManagementDTO) throws XbbException {
        MarketingManagementDataUpdateGetVO managementDataUpdateGetVO = new MarketingManagementDataUpdateGetVO();
        Long dataId = marketingManagementDTO.getDataId();
        String corpid = marketingManagementDTO.getCorpid();
        Integer subBusinessType = marketingManagementDTO.getSubBusinessType();
        PaasFormDataEntityExt paasFormDataEntityExt = null;
        JSONObject data = new JSONObject();
        if (Objects.equals(subBusinessType, XbbRefTypeEnum.MARKETING_ACTIVITY_MANAGEMENT.getCode())) {
            paasFormDataEntityExt = couponTempleteModel.getByKey(dataId, corpid);
            data = paasFormDataEntityExt.getData();
            String name = marketingHelp.analysisCouponName(paasFormDataEntityExt.getName(), corpid, paasFormDataEntityExt.getBusinessType());
            data.put(MarketingActivityManagementEnum.NAME.getAttr(), name);
            if (Objects.equals(data.getString(MarketingBaseEnum.INAPPLICABLE_PRODUCT_TYPE.getAttr()), InapplicableProductTypeEnum.FIXED_PRODUCT.getCode())) {
                ///解析不可用产品
                JSONArray resultArray = marketingHelp.analysisDisableProduct(data, corpid, null);
                data.put(MarketingBaseEnum.INAPPLICABLE_PRODUCT.getAttr(), resultArray);
            }
        }else if (Objects.equals(subBusinessType, XbbRefTypeEnum.PROMOTION_ACTIVITY_MANAGEMENT.getCode())){
            paasFormDataEntityExt = promotionActivityModel.getByKey(dataId, corpid);
            data = paasFormDataEntityExt.getData();
            ///解析可用产品
            JSONArray resultArray = marketingHelp.analysisPromotionProduct(paasFormDataEntityExt, corpid, null);
            data.put(MarketingBaseEnum.APPLICABLE_PRODUCT.getAttr(), resultArray);
            managementDataUpdateGetVO.setPriorityLevel(marketingHelp.getPriorityLevel(corpid, paasFormDataEntityExt.getBusinessType()));
        }

        Integer businessType = paasFormDataEntityExt.getBusinessType();

        //解析区域字段
        Map<Long, String> distributorAreaMap = marketingHelp.analysisLocation(data, corpid);

        List<ItemPoJo> distributorLevel = marketingHelp.getDistributorLevel(corpid);
        if (Objects.equals(data.getString(MarketingBaseEnum.APPLICABLE_OBJECT_TYPE.getAttr()), ApplicableObjectTypeEnum.SPECIFIC_DISTRIBUTOR.getCode())) {
            //解析具体经销商
            JSONArray distributorArray = marketingHelp.analysisDistributor(data, corpid, distributorLevel, distributorAreaMap, null);
            data.put(MarketingBaseEnum.DISTRIBUTOR.getAttr(), distributorArray);
        }
        managementDataUpdateGetVO.setBusinessType(businessType);
        managementDataUpdateGetVO.setData(data);
        managementDataUpdateGetVO.setDistributorLevel(distributorLevel);
        //为了选择产品
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getSystemDefaultExplain(businessType);
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        //处理关联产品解释
        handleProductExplain(explainList, marketingManagementDTO);
        managementDataUpdateGetVO.setExplainList(explainList);
        return managementDataUpdateGetVO;
    }

    @Override
    public MarketingManagementDataCopyVO copy(MarketingManagementDataCopyDTO marketingManagementDTO) throws XbbException {
        MarketingManagementDataCopyVO marketingManagementDataCopyVO = new MarketingManagementDataCopyVO();
        Long dataId = marketingManagementDTO.getDataId();
        String corpid = marketingManagementDTO.getCorpid();
        Integer subBusinessType = marketingManagementDTO.getSubBusinessType();
        PaasFormDataEntityExt paasFormDataEntityExt = null;
        JSONObject data = new JSONObject();
        if (Objects.equals(subBusinessType, XbbRefTypeEnum.MARKETING_ACTIVITY_MANAGEMENT.getCode())) {
            paasFormDataEntityExt = couponTempleteModel.getByKey(dataId, corpid);
            data = paasFormDataEntityExt.getData();
            String name = marketingHelp.analysisCouponName(paasFormDataEntityExt.getName(), corpid, paasFormDataEntityExt.getBusinessType());
            data.put(MarketingActivityManagementEnum.NAME.getAttr(), name);
            if (Objects.equals(data.getString(MarketingBaseEnum.INAPPLICABLE_PRODUCT_TYPE.getAttr()), InapplicableProductTypeEnum.FIXED_PRODUCT.getCode())) {
                ///解析不可用产品
                JSONArray resultArray = marketingHelp.analysisDisableProduct(data, corpid, null);
                data.put(MarketingBaseEnum.INAPPLICABLE_PRODUCT.getAttr(), resultArray);
            }
        }else if (Objects.equals(subBusinessType, XbbRefTypeEnum.PROMOTION_ACTIVITY_MANAGEMENT.getCode())){
            paasFormDataEntityExt = promotionActivityModel.getByKey(dataId, corpid);
            data = paasFormDataEntityExt.getData();
            ///解析可用产品
            JSONArray resultArray = marketingHelp.analysisPromotionProduct(paasFormDataEntityExt, corpid, null);
            data.put(MarketingBaseEnum.APPLICABLE_PRODUCT.getAttr(), resultArray);
            marketingManagementDataCopyVO.setPriorityLevel(marketingHelp.getPriorityLevel(corpid, paasFormDataEntityExt.getBusinessType()));
        }
        Integer businessType = paasFormDataEntityExt.getBusinessType();

        //解析区域字段
        Map<Long, String> distributorAreaMap = marketingHelp.analysisLocation(data, corpid);
        List<ItemPoJo> distributorLevel = marketingHelp.getDistributorLevel(corpid);
        if (Objects.equals(data.getString(MarketingBaseEnum.APPLICABLE_OBJECT_TYPE.getAttr()), ApplicableObjectTypeEnum.SPECIFIC_DISTRIBUTOR.getCode())) {
            //解析具体经销商
            JSONArray distributorArray = marketingHelp.analysisDistributor(data, corpid, distributorLevel, distributorAreaMap, null);
            data.put(MarketingBaseEnum.DISTRIBUTOR.getAttr(), distributorArray);
        }

        //复制不给活动时间
        data.put(MarketingBaseEnum.BEGIN_TIME.getAttr(), null);
        data.put(MarketingBaseEnum.END_TIME.getAttr(), null);
        //复制时候固定日期也置空，避免出现已过期的日期
        data.put(MarketingBaseEnum.VALIDITY_TIME.getAttr(),null);
        marketingManagementDataCopyVO.setBusinessType(businessType);
        marketingManagementDataCopyVO.setData(data);
        marketingManagementDataCopyVO.setDistributorLevel(distributorLevel);
        //为了选择产品
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getSystemDefaultExplain(businessType);
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        //处理关联产品解释
        handleProductExplain(explainList, marketingManagementDTO);
        marketingManagementDataCopyVO.setExplainList(explainList);
        return marketingManagementDataCopyVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MarketingManagementDataUpdateVO update(MarketingManagementDataUpdateDTO marketingManagementDTO) throws XbbException {

        MarketingManagementDataUpdateVO marketingManagementDataUpdateVO = new MarketingManagementDataUpdateVO();
        try {
            Integer businessType = marketingManagementDTO.getBusinessType();
            JSONObject data = marketingManagementDTO.getDataList();
            //校验数据格式
            validateData(data, businessType);

            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
            AfterSaveVO afterSaveVO;
            switch (xbbRefTypeEnum) {
                case FULL_DISCOUNT_COUPON:
                    afterSaveVO = couponTempleteService.update(marketingManagementDTO);
                    break;
                case SPECIAL_GOODS:
                    afterSaveVO = promotionActivityService.update(marketingManagementDTO);
                    break;
                default:
                    afterSaveVO = new AfterSaveVO();
            }
            if ( Objects.equals(afterSaveVO.getCode(), PaasConstant.FORM_ADD_PROCESS_RETURN_CODE) ) {
                marketingManagementDataUpdateVO.setMsg(afterSaveVO.getMsg());
                marketingManagementDataUpdateVO.setCode(afterSaveVO.getCode());
            }else {
                marketingManagementDataUpdateVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_RETURN_MSG));
                marketingManagementDataUpdateVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("MarketingManagement数据库编辑保存表单数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return marketingManagementDataUpdateVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MarketingManagementDeleteBatchVO deleteBatch(MarketingManagementDeleteBatchDTO marketingManagementDeleteBatchDTO) throws XbbException {
        MarketingManagementDeleteBatchVO marketingManagementDeleteBatchVO = null;
        try {
            Integer subBusinessType = marketingManagementDeleteBatchDTO.getSubBusinessType();
            marketingManagementDeleteBatchVO = new MarketingManagementDeleteBatchVO();
            if (Objects.equals(subBusinessType, XbbRefTypeEnum.MARKETING_ACTIVITY_MANAGEMENT.getCode())) {
                marketingManagementDeleteBatchVO = couponTempleteService.deleteBatch(marketingManagementDeleteBatchDTO);
            }else if (Objects.equals(subBusinessType, XbbRefTypeEnum.PROMOTION_ACTIVITY_MANAGEMENT.getCode())){
                marketingManagementDeleteBatchVO = promotionActivityService.deleteBatch(marketingManagementDeleteBatchDTO);
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("MarketingManagementService.deleteBatch批量删除出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return marketingManagementDeleteBatchVO;
    }

    @Override
    public BaseVO online(OnlineDTO onlineDTO) throws XbbException {
        Integer businessType = onlineDTO.getBusinessType();
        if (Objects.equals(businessType, XbbRefTypeEnum.MARKETING_ACTIVITY_MANAGEMENT.getCode())) {
            couponTempleteService.online(onlineDTO);
        }else if (Objects.equals(businessType, XbbRefTypeEnum.PROMOTION_ACTIVITY_MANAGEMENT.getCode())){
            promotionActivityService.online(onlineDTO);
        }
        return new BaseVO();
    }

    @Override
    public MobileFormCommonDetailVO getMoblieDetail(FormDataGetDTO formDataGetDTO) throws XbbException {
        MobileFormCommonDetailVO mobileFormCommonDetailVO = new MobileFormCommonDetailVO();
        Integer subBusinessType = formDataGetDTO.getBusinessType();
        VerifyViewPermissionDTO verifyViewPermissionDTO = new VerifyViewPermissionDTO();
        BeanUtil.copyProperties(formDataGetDTO, verifyViewPermissionDTO);
        verifyViewPermissionDTO.setMenuId(formDataGetDTO.getMenuId());
        ProPermissionHelp.verifyQueryPermission(verifyViewPermissionDTO);
        Long dataId = formDataGetDTO.getDataId();
        String corpid = formDataGetDTO.getCorpid();
        UserVO loginUser = formDataGetDTO.getLoginUser();
        List<DetailTabPojo> tabPojoList = new ArrayList<>();
        PaasFormDataEntityExt paasFormDataEntityExt = null;
        if (Objects.equals(subBusinessType, XbbRefTypeEnum.MARKETING_ACTIVITY_MANAGEMENT.getCode())) {
            paasFormDataEntityExt = couponTempleteModel.getByKey(dataId, corpid);
        }else if (Objects.equals(subBusinessType, XbbRefTypeEnum.PROMOTION_ACTIVITY_MANAGEMENT.getCode())){
            paasFormDataEntityExt = promotionActivityModel.getByKey(dataId, corpid);
        }
        Integer businessType = paasFormDataEntityExt.getBusinessType();
        JSONObject data = paasFormDataEntityExt.getData();
        Integer status = paasFormDataEntityExt.getStatus();
        //tab处理
        marketingHelp.handelDetailTab(businessType, tabPojoList, PlatFormEnum.DINGTALK, loginUser, data, corpid);
        mobileFormCommonDetailVO.setTabList(tabPojoList);
        //顶部操作处理
        List<TopPermissionsPoJo> topPermissions = marketingHelp.handelMobileWorkFlow(businessType, loginUser, status, subBusinessType, corpid);
        mobileFormCommonDetailVO.setTopPermissions(topPermissions);
        List<SummaryDataPoJo> summaryList = new ArrayList<>();
        Long beginTime = FastJsonHelper.getLongOrDefaultFromFormData(data, MarketingBaseEnum.BEGIN_TIME.getAttr(),0L);
        Long endTime = FastJsonHelper.getLongOrDefaultFromFormData(data, MarketingBaseEnum.END_TIME.getAttr(),0L);
        String beginTimeStr = DateTimeUtil.getDateStringEpochSecond(beginTime);
        String endTimeStr = DateTimeUtil.getDateStringEpochSecond(endTime);
        String addTime = DateTimeUtil.getDateStringEpochSecond(paasFormDataEntityExt.getAddTime());
        UserEntity userEntity = userModel.getByKey(paasFormDataEntityExt.getCreatorId(), corpid);
        String creatorName = "";
        if (Objects.nonNull(userEntity)) {
            creatorName = userEntity.getName();
        }
        summaryList.add(new SummaryDataPoJo(MarketingBaseEnum.TYPE.getAttr(),MarketingBaseEnum.TYPE.getAttrName(),MarketingBaseEnum.TYPE.getFieldType(), Collections.singletonList(XbbRefTypeEnum.getByCode(businessType).getName())));
        summaryList.add(new SummaryDataPoJo(MarketingBaseEnum.ACTIVITY_TIME.getAttr(),MarketingBaseEnum.ACTIVITY_TIME.getAttrName(),MarketingBaseEnum.ACTIVITY_TIME.getFieldType(), Collections.singletonList(String.format(StringConstant.TIME_RANGE, beginTimeStr, endTimeStr))));
        summaryList.add(new SummaryDataPoJo(MarketingBaseEnum.CREATOR_ID.getAttr(),MarketingBaseEnum.CREATOR_ID.getAttrName(),MarketingBaseEnum.CREATOR_ID.getFieldType(), Collections.singletonList(creatorName)));
        summaryList.add(new SummaryDataPoJo(MarketingBaseEnum.ADD_TIME.getAttr(),MarketingBaseEnum.ADD_TIME.getAttrName(),MarketingBaseEnum.ADD_TIME.getFieldType(), Collections.singletonList(addTime)));

        List<FormTitlePoJo> titleList = new ArrayList<>();
        titleList.add(new FormTitlePoJo(MarketingBaseEnum.NAME.getAttr(), null, MarketingBaseEnum.NAME.getAttrName(), Collections.singletonList(data.getString(MarketingBaseEnum.NAME.getAttr())), null));
        mobileFormCommonDetailVO.setTitleList(titleList);
        mobileFormCommonDetailVO.setSummaryList(summaryList);
        MobileDetailSpecialInfoPojo mobileDetailSpecialInfoPojo = new MobileDetailSpecialInfoPojo();
        MobileDetailStatusPojo mobileDetailStatusPojo = new MobileDetailStatusPojo(StringConstant.ONLINE, status);
        mobileDetailSpecialInfoPojo.setStatus(mobileDetailStatusPojo);
        mobileFormCommonDetailVO.setRightSpecialInfo(mobileDetailSpecialInfoPojo);
        mobileFormCommonDetailVO.setBottomBlockInfo(new JSONArray());
        mobileFormCommonDetailVO.setPaasFormEntity(new PaasFormEntity());
        mobileFormCommonDetailVO.setData(data);
        return mobileFormCommonDetailVO;
    }




    private Boolean checkDataPermission(FormDataDetailDTO formDataDetailDTO) {

        UserVO loginUser = formDataDetailDTO.getLoginUser();
        if (loginUser.isMaxDataPermission()){
            return true;
        }
        Long dataId = formDataDetailDTO.getDataId();



        return null;
    }




    private void handleProductExplain(List<FieldAttrEntity> productExplain,MarketingManagementDTO managementDTO) throws XbbException {
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(managementDTO.getBusinessType());
        PaasFormEntity paasFormEntity = paasFormModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), managementDTO.getCorpid());
        for (FieldAttrEntity fieldAttrEntity : productExplain) {
            if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.SELECT_PRODUCT.getType())) {
                List<? extends FieldAttrEntity> subExplainList = fieldAttrEntity.getSubForm().getItems();
                Iterator<? extends FieldAttrEntity> iterator = subExplainList.iterator();
                while (iterator.hasNext()){
                    FieldAttrEntity subFieldAttrEntity = iterator.next();
                    if (!Objects.equals(subFieldAttrEntity.getAttr(), SelectProductEnum.PRODUCT.getAttr())){
                        continue;
                    }
                    subFieldAttrEntity.getLinkInfo().setLinkAppId(paasFormEntity.getAppId());
                    subFieldAttrEntity.getLinkInfo().setLinkMenuId(paasFormEntity.getMenuId());
                    subFieldAttrEntity.getLinkInfo().setLinkFormId(paasFormEntity.getId());
                    break;
                }
                explainHelp.formatSelectProductExplains(fieldAttrEntity, xbbRefTypeEnum, managementDTO.getCorpid(), BasicConstant.TWO, true);
            }
        }

    }

    /**
     * 校验数据和过滤数据和公用校验
     * @param data
     * @param businessType
     * @throws XbbException
     */
    public void validateData(JSONObject data, Integer businessType) throws XbbException {
        Map<String, FieldAttrEntity> fieldMap = marketingFieldHelp.getFieldMapByBusinessType(businessType);
        for (FieldAttrEntity entity : fieldMap.values()) {
            String attr = entity.getAttr();
            Integer fieldType = entity.getFieldType();
            String value = data.getString(attr);
            //字段必填校验
            if (Objects.equals(entity.getRequired(), BasicConstant.ONE) && StringUtil.isEmpty(data.getString(attr))) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FIELD_MUST_REQUIRED, entity.getAttrName());
            }
            if (Objects.equals(fieldType, FieldTypeEnum.RICH_TEXT_EDITOR.getType())) {
                String memo = data.getString(attr);
                memo = StringUtil.filterEmoji(memo);
                if (memo.length() > BasicConstant.MARKETING_MAX_LENGTH) {
                    throw new XbbException(MarketingErrorCodeEnum.API_ERROR_1500008);
                }
            } else if(Objects.equals(fieldType, FieldTypeEnum.NUM.getType())){
                if (value != null) {
                    if (value.length() > AliasEnum.NUM.getMax()) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MORE_THAN_LENGTH, entity.getAttrName(), AliasEnum.NUM.getMax());
                    }
                }
                String numStr = data.getString(attr);
                if (StringUtil.isEmpty(numStr)) {
                    data.put(attr, null);
                    continue;
                }
                Double num = null;
                try {
                    BigDecimal bigDecimal = new BigDecimal(numStr);
                    num = bigDecimal.doubleValue();
                } catch (NumberFormatException e) {
                    LOG.error("MarketingManagement validateData error:" + numStr + ",key:" + attr + ",explainMap:" + fieldMap.get(attr).getAttrName());
                    LOG.error("MarketingManagement validateData error",e);
                    num = null;
                }
                // 校验数据是否是数字
                if(num == null){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, MessageConstant.DATA_NOT_STANDARD, fieldMap.get(attr).getAttrName());
                }
            }else if(Objects.equals(fieldType, FieldTypeEnum.DATETIME.getType())){
                if (StringUtil.isEmpty(value)) {
                 data.remove(attr);
                }else {
                    try {
                        Integer.parseInt(value);
                    } catch (NumberFormatException e) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, MessageConstant.DATA_NOT_STANDARD, fieldMap.get(attr).getAttrName());
                    }
                }
            }
        }
        //过滤数据
        Iterator<String> iterator = data.keySet().iterator();
        while (iterator.hasNext()){
            String str = iterator.next();
            if (!fieldMap.containsKey(str)) {
                iterator.remove();
            }
        }
        if (data.getLong(MarketingBaseEnum.END_TIME.getAttr()) - data.getLong(MarketingBaseEnum.BEGIN_TIME.getAttr()) > TimeConstant.SECONDS_PER_LONG_YEAR) {
            throw new XbbException(MarketingErrorCodeEnum.API_ERROR_1500030);
        }
        if (data.getString(MarketingBaseEnum.NAME.getAttr()).length() > 100) {
            throw new XbbException(MarketingErrorCodeEnum.API_ERROR_1500013);
        }
    }

}
